package com.rk.cust.infra.persistence;

import com.rk.cust.common.exception.CustException;
import com.rk.cust.common.exception.ErrorCode;
import com.rk.cust.domain.entity.Cust;
import com.rk.cust.infra.persistence.assembler.CustPoAssembler;
import com.rk.cust.infra.persistence.po.CustPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

@Repository
public class CustRepository {

    @Autowired
    private JpaCustRepository jpaCustRepository;

    @Autowired
    private CustPoAssembler custPoAssembler;

    public Cust queryCustById(Long id) {
        CustPo custPo = jpaCustRepository.findById(Long.valueOf(id)).orElse(null);
        if (null == custPo) {
            return new Cust();
        } else {
            return custPoAssembler.assembler(custPo);
        }
    }

    public void addCust(Cust cust) {
        CustPo custPo = custPoAssembler.assembler(cust);
        custPo.setId(System.currentTimeMillis());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        custPo.setCreateTime(now);
        custPo.setLastUpdateTime(now);
        jpaCustRepository.save(custPo);
    }

    @Transactional
    public void updateCust(Cust cust) {
        CustPo custPo = custPoAssembler.assembler(cust);
        custPo.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
        int count = jpaCustRepository.updateCust(custPo);
        System.out.println(count);
        if (1 != count) {
            throw new CustException(ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }

}